<?php

namespace app\modules\merchant\services;

use app\common\services\BaseService;
use app\models\GoodsCategory;
use app\modules\merchant\forms\category\GoodsCategoryForm;

class GoodsCategoryService extends BaseService{

    /**
     * 搜索
     * @param $merchant_id
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function search($merchant_id){
        return GoodsCategory::find()->andWhere(['merchant_id'=>$merchant_id])->orderBy(['sort'=>SORT_ASC])->all();
    }

    /**
     * 创建
     * @param GoodsCategoryForm $form
     * @return bool
     * @throws \Throwable
     */
    public static function create(GoodsCategoryForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model = new GoodsCategory();
        $model->setAttributes($form->getAttributes(),false);

        return $model->insert() !== false;
    }

    /**
     * 获取信息
     * @param $merchant_id
     * @param $id
     * @return null|GoodsCategory
     */
    public static function getInfoById($merchant_id,$id){
        return GoodsCategory::findOne(['merchant_id'=>$merchant_id,'cat_id'=>$id]);
    }

    /**
     * 更新
     * @param GoodsCategoryForm $form
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function update(GoodsCategoryForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model = GoodsCategory::findOne(['cat_id'=>$form->cat_id]);
        if(!$model){
            self::setError(\Yii::t("app","分类不存在"));
            return false;
        }

        $model->setAttributes($form->getAttributes(),false);
        return $model->update() !== false;
    }

    /**
     * 删除
     * @param $merchant_id
     * @param $id
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function delete($merchant_id,$id){
        GoodsCategory::deleteAll(['merchant_id'=>$merchant_id,'cat_id'=>$id]);
    }
}